package achao.gallary.com.normalgallary;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Parcelable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PhotoViewActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private List<ImageBean> imageBeanList;
    private ArrayList<AnimationRect> rectList;
    private int position = 0;
    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    public static Intent newIntent(Context context, ArrayList<ImageBean> urls, ArrayList<AnimationRect> rectList,
                                   int initPosition) {
        Intent intent = new Intent(context, PhotoViewActivity.class);
        intent.putExtra("datas", urls);
        intent.putExtra("rect", rectList);
        intent.putExtra("position", initPosition);
        return intent;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_view);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        Intent intent = getIntent();
        imageBeanList = intent.getParcelableArrayListExtra("datas");
        position = intent.getIntExtra("position", 0);
        rectList = getIntent().getParcelableArrayListExtra("rect");
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setCurrentItem(position);
        background = getAppContentView(this);

    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private ImageView photos;
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(ImageBean imageBean) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putParcelable(ARG_SECTION_NUMBER, imageBean);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public String toString() {
            return super.toString();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_photo_view, container, false);
            photos = (ImageView) rootView.findViewById(R.id.iv_photos);
            ImageBean imageBean = getArguments().getParcelable(ARG_SECTION_NUMBER);
            Glide.with(photos.getContext())
                    .load(imageBean.getImageUrl())
                    .into(photos);
            return rootView;
        }
    }
    private boolean alreadyAnimateIn = false;
    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            ContainerFragment fragment = fragmentMap.get(position);
            if (fragment == null) {

                boolean animateIn = (PhotoViewActivity.this.position == position) && !alreadyAnimateIn;
                fragment = ContainerFragment
                        .newInstance(imageBeanList.get(position).getImageUrl(), rectList.get(position), animateIn,
                                PhotoViewActivity.this.position == position);
                alreadyAnimateIn = true;
                fragmentMap.put(position, fragment);
            }
           // PlaceholderFragment.newInstance(imageBeanList.get(position));
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return imageBeanList.size();
        }
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
            if (object instanceof Fragment) {
                fragmentMap.put(position, (ContainerFragment) object);
            }
        }

    }

    private View background;
    private ColorDrawable backgroundColor;

    public void showBackgroundImmediately() {
        if (background.getBackground() == null) {
            backgroundColor = new ColorDrawable(Color.BLACK);
            background.setBackground(backgroundColor);
        }
    }

    public ObjectAnimator showBackgroundAnimate() {
        backgroundColor = new ColorDrawable(Color.BLACK);
        background.setBackground(backgroundColor);
        ObjectAnimator bgAnim = ObjectAnimator
                .ofInt(backgroundColor, "alpha", 0, 255);
        bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                background.setBackground(backgroundColor);
            }
        });
        return bgAnim;
    }

    public static View getAppContentView(Activity activity) {
        final View appView = activity.findViewById(android.R.id.content);
        return appView;
    }
    private HashMap<Integer, ContainerFragment> fragmentMap
            = new HashMap<Integer, ContainerFragment>();
    @Override
    public void onBackPressed() {

        ContainerFragment fragment = fragmentMap.get(mViewPager.getCurrentItem());
        if (fragment != null && fragment.canAnimateCloseActivity()) {
            backgroundColor = new ColorDrawable(Color.BLACK);
            ObjectAnimator bgAnim = ObjectAnimator.ofInt(backgroundColor, "alpha", 0);
            bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    background.setBackground(backgroundColor);
                }
            });
            bgAnim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    PhotoViewActivity.super.finish();
                    overridePendingTransition(-1, -1);
                }
            });
            fragment.animationExit(bgAnim);
        } else {
            super.onBackPressed();
        }
    }

}
